import * as reactiveUtils from "@geoscene/core/core/reactiveUtils";
import * as ReactDOM from "react-dom";
import useMap2D from "@/hooks/map/useMap2D";

import "./index.less";

// 定义 Props 类型
interface LayerPopUp {
  title: string;
  attributes: { longitude: number; latitude: number;[key: string]: any };
  parent?: HTMLElement;
  template: React.ReactNode;
  onClose: () => void;
  bottomNode?: React.ReactNode;
}

// 设置 popup 位置
function setDomPosition(
  view2D: any,
  attributes: any,
  wholeDivRef: any,
  setWholePosition: any,
  setTipPosition: any
) {
  // 1. 计算 popup 位置
  let initCoord = view2D.toScreen({
    x: attributes.longitude,
    y: attributes.latitude,
    spatialReference: { wkid: 4326 },
  });
  // 2. 设置 popup 位置
  if (wholeDivRef.current) {
    setWholePosition({
      top: initCoord.y - wholeDivRef.current.offsetHeight - 10,
      left: initCoord.x - wholeDivRef.current.offsetWidth / 2,
    });

    setTipPosition({
      top: wholeDivRef.current.offsetHeight - 2,
      left: wholeDivRef.current.offsetWidth / 2 - 10,
    });
  }
}

const LayerPopUp = ({
  title,
  attributes,
  template,
  parent: parentDom,
  onClose,
  bottomNode,
}: LayerPopUp) => {
  // 1.创建ref 来引用 div 元素
  const wholeDivRef = useRef<HTMLDivElement>(null);
  const tipDivRef = useRef<HTMLDivElement>(null);

  // 2.使用 state 存储位置信息
  const [wholePosition, setWholePosition] = useState({ top: 20, left: 20 });
  const [tipPosition, setTipPosition] = useState({ top: 20, left: 20 });

  const { view2D } = useMap2D();

  // 3.获取父元素 (这里可以优化，每次渲染都会查询)
  const parent = parentDom || document.querySelector("body");

  // 4.监听 view2D 的 extent 变化，更新 popup 位置
  useEffect(() => {
    // 如果 view2D 不存在，则不进行监听
    if (!view2D) return;

    setDomPosition(
      view2D,
      attributes,
      wholeDivRef,
      setWholePosition,
      setTipPosition
    );

    const watchHandle = reactiveUtils.watch(
      () => view2D.extent,
      () => {
        setDomPosition(
          view2D,
          attributes,
          wholeDivRef,
          setWholePosition,
          setTipPosition
        );
      }
    );

    // 返回清理函数，在组件卸载时移除监听
    return () => {
      watchHandle.remove();
    };
  }, [view2D, attributes, parent]); // 添加依赖项

  const onCloseFn = () => {
    onClose && onClose();
  };

  // 5.创建 popup 元素
  const popupElement = (
    <div
      className="gis-icon-label-layer-container"
      ref={wholeDivRef}
      style={{
        position: "absolute",
        top: wholePosition.top,
        left: wholePosition.left,
      }}
    >
      <div className="header">
        <div className="title">{title}</div>
        <div className="close-btn" onClick={onCloseFn}>
          ×
        </div>
      </div>
      <div className="content">{template}</div>
      <div className="bottom">{bottomNode ? bottomNode : ""}</div>
      <div
        className="layer-icon"
        ref={tipDivRef}
        style={{
          position: "absolute",
          top: tipPosition.top,
          left: tipPosition.left,
        }}
      ></div>
      <div className="corner-icon top-left"></div>
      <div className="corner-icon top-right"></div>
      <div className="corner-icon bottom-left"></div>
      <div className="corner-icon bottom-right"></div>
    </div>
  );

  // 6. 正确使用 createPortal 并返回
  if (!view2D || !parent) {
    // 如果父元素不存在，可以选择返回 null 或一个占位符
    return null;
  }

  return ReactDOM.createPortal(popupElement, parent);
};

export default LayerPopUp;
